package com.echo.im.server.netty.processor.impl;

import com.echo.im.common.enums.IMCmdType;
import com.echo.im.common.model.IMRecvInfo;
import com.echo.im.common.model.IMSendInfo;
import com.echo.im.common.model.IMUserInfo;
import com.echo.im.common.vo.message.GroupMessageVO;
import com.echo.im.server.netty.context.UserChannelMap;
import com.echo.im.server.netty.processor.AbstractMessageProcessor;
import io.netty.channel.Channel;
import io.netty.channel.ChannelHandlerContext;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import java.util.List;
import java.util.Objects;

/**
 *
 * @author echo
 * @date 2024-08-18
 */
@Slf4j
@Component
@RequiredArgsConstructor
public class GroupMessageProcessor extends AbstractMessageProcessor<IMRecvInfo<GroupMessageVO>> {


    @Override
    public void process(ChannelHandlerContext ctx, IMRecvInfo<GroupMessageVO> recvInfo) {

        IMUserInfo sender = recvInfo.getSender();
        List<IMUserInfo> receivers = recvInfo.getReceivers();
        log.info("接收到群消息，发送者:{},接收用户数量:{}，内容:{}", sender.getId(), receivers.size(), recvInfo.getData());
        for (IMUserInfo receiver : receivers) {
            try {
                Channel channel = UserChannelMap.getChannel(receiver.getId(), receiver.getTerminal());
                //Channel为null，则证明用户不在线，不用管
                if (Objects.isNull(channel)) {
                    log.error("未找到channel,发送者:{},接收id:{}，内容:{}", sender.getId(), receiver.getId(), recvInfo.getData());
                    continue;
                }

                // 推送消息到用户
                IMSendInfo<GroupMessageVO> sendInfo = new IMSendInfo<>();
                sendInfo.setCmd(IMCmdType.GROUP_MESSAGE.code());
                sendInfo.setData(recvInfo.getData());
                channel.writeAndFlush(sendInfo);

            } catch (Exception e) {

                log.error("发送消息异常,发送者:{},接收id:{}，内容:{}", sender.getId(), receiver.getId(), recvInfo.getData());
            }
        }
    }

    @Override
    public void process(IMRecvInfo data) {

    }

    @Override
    public IMCmdType getCmdType() {
        return IMCmdType.GROUP_MESSAGE;
    }


}
